# coding=utf-8
import os
import commands


def log_deco(func):
    """
    log the func result before return
    :param func:
    :return:
    """

    def _log_deco(*args, **kwargs):
        ret = func(*args, **kwargs)
        print(ret[1])
        return ret

    return _log_deco


@log_deco
def zip_dir(dir_name, zip_filename):
    if not os.path.exists(dir_name):
        return 1, "dir_name not exist"
    parent_dir = os.path.dirname(dir_name)
    dir_name_without_path = dir_name[len(parent_dir)+1:]
    cmd_7zip = "7za a {0} {1}".format(zip_filename, dir_name)
    cmd_zip = "cd {0}; zip -r {1} {2}".format(parent_dir, zip_filename, dir_name_without_path)
    return commands.getstatusoutput(cmd_zip)



@log_deco
def unzip_file(zip_filename, unzip_2_dir):
    """
    unzip and overwrite

    :param zip_filename:
    :param unzip_2_dir: must be unzip_2_dir's parent directory
    :return:
    """
    if not os.path.exists(zip_filename):
        return 1, "zip_filename not exist"

    parent_dir = os.path.dirname(zip_filename)
    zip_filename_without_path = zip_filename[len(parent_dir)+1:]
    cmd_7zip = "cd {0}; 7za -aoa x {1}".format(unzip_2_dir, zip_filename)
    cmd_zip = "cd {0}; unzip -o {1} -d {2}".format(parent_dir, zip_filename_without_path, unzip_2_dir)
    return commands.getstatusoutput(cmd_zip)


if __name__ == "__main__":

    zip_dir(r"/Users/zhangmike/Desktop/datamigrate", r"/Users/zhangmike/Desktop/datamigrate.zip")
    unzip_file(r"/Users/zhangmike/Desktop/datamigrate.zip", r"/Users/zhangmike/Desktop/")
